package mgo

import (
	"reflect"
	"time"
)

type LoadingPool struct {
	Models map[string]map[int64]PoolModel
}

type PoolModel struct {
	Id    int64
	Ts    int64
	Model interface{}
}

var loadingPool LoadingPool

func GetLoadingPool() *LoadingPool {
	return &loadingPool
}

func init() {
	loadingPool = LoadingPool{
		Models: make(map[string]map[int64]PoolModel),
	}
}

func (p *LoadingPool) Set(m interface{}) {
	vo := reflect.ValueOf(m).Elem()
	if vo.FieldByName("Id").IsValid() {
		id := vo.FieldByName("Id").Int()
		tp := reflect.TypeOf(m)
		if p.Models[tp.String()] == nil {
			p.Models[tp.String()] = make(map[int64]PoolModel)
		}
		p.Models[tp.String()][id] = PoolModel{
			Id:    id,
			Model: m,
			Ts:    time.Now().Unix(),
		}
	}
}

func (p *LoadingPool) Get(id int64, value interface{}) bool {
	tp := reflect.TypeOf(value)
	if find, ok := p.Models[tp.String()]; ok {
		if pm, idOK := find[id]; idOK {
			if time.Now().Unix()-pm.Ts < 5 {
				reflect.ValueOf(value).Elem().Set(reflect.ValueOf(pm.Model).Elem())
				return true
			} else {
				return false
			}

		} else {
			return false
		}
	}
	return false
}
